home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / components / nsHelperAppDlg.js < prev    next >
Encoding:
JavaScript  |  2007-11-12  |  35.4 KB  |  940 lines

  1. /*
  2. //@line 42 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  3. */
  4.  
  5. /* This file implements the nsIHelperAppLauncherDialog interface.
  6.  *
  7.  * The implementation consists of a JavaScript "class" named nsUnknownContentTypeDialog,
  8.  * comprised of:
  9.  *   - a JS constructor function
  10.  *   - a prototype providing all the interface methods and implementation stuff
  11.  *
  12.  * In addition, this file implements an nsIModule object that registers the
  13.  * nsUnknownContentTypeDialog component.
  14.  */
  15.  
  16.  
  17. /* ctor
  18.  */
  19. function nsUnknownContentTypeDialog() {
  20.     // Initialize data properties.
  21.     this.mLauncher = null;
  22.     this.mContext  = null;
  23.     this.mSourcePath = null;
  24.     this.chosenApp = null;
  25.     this.givenDefaultApp = false;
  26.     this.updateSelf = true;
  27.     this.mTitle    = "";
  28. }
  29.  
  30. nsUnknownContentTypeDialog.prototype = {
  31.     nsIMIMEInfo  : Components.interfaces.nsIMIMEInfo,
  32.  
  33.     // This "class" supports nsIHelperAppLauncherDialog, and nsISupports.
  34.     QueryInterface: function (iid) {
  35.         if (!iid.equals(Components.interfaces.nsIHelperAppLauncherDialog) &&
  36.             !iid.equals(Components.interfaces.nsISupports)) {
  37.             throw Components.results.NS_ERROR_NO_INTERFACE;
  38.         }
  39.         return this;
  40.     },
  41.  
  42.     // ---------- nsIHelperAppLauncherDialog methods ----------
  43.  
  44.     // show: Open XUL dialog using window watcher.  Since the dialog is not
  45.     //       modal, it needs to be a top level window and the way to open
  46.     //       one of those is via that route).
  47.     show: function(aLauncher, aContext, aReason)  {
  48.       this.mLauncher = aLauncher;
  49.       this.mContext  = aContext;
  50.       // Display the dialog using the Window Watcher interface.
  51.       
  52.       var ir = aContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor);
  53.       var dwi = ir.getInterface(Components.interfaces.nsIDOMWindowInternal);
  54.       var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]
  55.                 .getService(Components.interfaces.nsIWindowWatcher);
  56.       this.mDialog = ww.openWindow(dwi,
  57.                                    "chrome://mozapps/content/downloads/unknownContentType.xul",
  58.                                    null,
  59.                                    "chrome,centerscreen,titlebar,dialog=yes,dependent",
  60.                                    null);
  61.       // Hook this object to the dialog.
  62.       this.mDialog.dialog = this;
  63.       
  64.       // Hook up utility functions. 
  65.       this.getSpecialFolderKey = this.mDialog.getSpecialFolderKey;
  66.       
  67.       // Watch for error notifications.
  68.       this.progressListener.helperAppDlg = this;
  69.       this.mLauncher.setWebProgressListener(this.progressListener);
  70.     },
  71.  
  72.     // promptForSaveToFile:  Display file picker dialog and return selected file.
  73.     //                       This is called by the External Helper App Service
  74.     //                       after the ucth dialog calls |saveToDisk| with a null
  75.     //                       target filename (no target, therefore user must pick).
  76.     //
  77.     //                       Alternatively, if the user has selected to have all
  78.     //                       files download to a specific location, return that
  79.     //                       location and don't ask via the dialog. 
  80.     //
  81.     // Note - this function is called without a dialog, so it cannot access any part
  82.     // of the dialog XUL as other functions on this object do. 
  83.     promptForSaveToFile: function(aLauncher, aContext, aDefaultFile, aSuggestedFileExtension) {
  84.       var result = "";
  85.       
  86.       this.mLauncher = aLauncher;
  87.  
  88.       // If the user is always downloading to the same location, the default download
  89.       // folder is stored in preferences. If a value is found stored, use that 
  90.       // automatically and don't ask via a dialog. 
  91.       var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  92.       var autodownload = prefs.getBoolPref("browser.download.useDownloadDir");
  93.       if (autodownload) {
  94.         function getSpecialFolderKey(aFolderType) 
  95.         {
  96.           if (aFolderType == "Desktop")
  97.             return "Desk";
  98.         
  99.           if (aFolderType != "Downloads")
  100.             throw "ASSERTION FAILED: folder type should be 'Desktop' or 'Downloads'";
  101.         
  102. //@line 142 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  103.           return "Pers";
  104. //@line 150 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  105.         }
  106.         
  107.         function getDownloadsFolder(aFolder)
  108.         {
  109.           var fileLocator = Components.classes["@mozilla.org/file/directory_service;1"].getService(Components.interfaces.nsIProperties);
  110.  
  111.           var dir = fileLocator.get(getSpecialFolderKey(aFolder), Components.interfaces.nsILocalFile);
  112.           
  113.           var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  114.           bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
  115.  
  116.           var description = bundle.GetStringFromName("myDownloads");
  117.           if (aFolder != "Desktop")
  118.             dir.append(description);
  119.             
  120.           return dir;
  121.         }
  122.  
  123.         var defaultFolder = null;
  124.         switch (prefs.getIntPref("browser.download.folderList")) {
  125.         case 0:
  126.           defaultFolder = getDownloadsFolder("Desktop");
  127.           break;
  128.         case 1:
  129.           defaultFolder = getDownloadsFolder("Downloads");
  130.           break;
  131.         case 2:
  132.           defaultFolder = prefs.getComplexValue("browser.download.dir", Components.interfaces.nsILocalFile);
  133.           break;
  134.         }
  135.         
  136.         result = this.validateLeafName(defaultFolder, aDefaultFile, aSuggestedFileExtension);
  137.       }
  138.       
  139.       if (!result) {
  140.         // Use file picker to show dialog.
  141.         var nsIFilePicker = Components.interfaces.nsIFilePicker;
  142.         var picker = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  143.  
  144.         var bundle = Components.classes["@mozilla.org/intl/stringbundle;1"].getService(Components.interfaces.nsIStringBundleService);
  145.         bundle = bundle.createBundle("chrome://mozapps/locale/downloads/unknownContentType.properties");
  146.  
  147.         var windowTitle = bundle.GetStringFromName("saveDialogTitle");
  148.         var parent = aContext.QueryInterface(Components.interfaces.nsIInterfaceRequestor).getInterface(Components.interfaces.nsIDOMWindowInternal);
  149.         picker.init(parent, windowTitle, nsIFilePicker.modeSave);
  150.         picker.defaultString = aDefaultFile;
  151.  
  152.         if (aSuggestedFileExtension) {
  153.           // aSuggestedFileExtension includes the period, so strip it
  154.           picker.defaultExtension = aSuggestedFileExtension.substring(1);
  155.         } 
  156.         else {
  157.           try {
  158.             picker.defaultExtension = this.mLauncher.MIMEInfo.primaryExtension;
  159.           } 
  160.           catch (ex) { }
  161.         }
  162.  
  163.         var wildCardExtension = "*";
  164.         if (aSuggestedFileExtension) {
  165.           wildCardExtension += aSuggestedFileExtension;
  166.           picker.appendFilter(this.mLauncher.MIMEInfo.description, wildCardExtension);
  167.         }
  168.  
  169.         picker.appendFilters( nsIFilePicker.filterAll );
  170.  
  171.         // Pull in the user's preferences and get the default download directory.
  172.         var prefs = Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
  173.         try {
  174.           var startDir = prefs.getComplexValue("browser.download.dir", Components.interfaces.nsILocalFile);
  175.           if (startDir.exists()) {
  176.             picker.displayDirectory = startDir;
  177.           }
  178.         } 
  179.         catch(exception) { }
  180.  
  181.         var dlgResult = picker.show();
  182.  
  183.         if (dlgResult == nsIFilePicker.returnCancel) {
  184.           // null result means user cancelled.
  185.           return null;
  186.         }
  187.  
  188.  
  189.         // Be sure to save the directory the user chose through the Save As... 
  190.         // dialog  as the new browser.download.dir
  191.         result = picker.file;
  192.  
  193.         if (result) {
  194.           var newDir = result.parent;
  195.           prefs.setComplexValue("browser.download.dir", Components.interfaces.nsILocalFile, newDir);
  196.         }
  197.       }
  198.       return result;
  199.     },
  200.     
  201.     validateLeafName: function (aLocalFile, aLeafName, aFileExt)
  202.     {
  203.       if (!aLocalFile || !aLocalFile.exists())
  204.         return null;
  205.  
  206.       if (aLeafName == "")
  207.         aLeafName = "unnamed" + (aFileExt ? "." + aFileExt : "");
  208.       aLocalFile.append(aLeafName);
  209.  
  210.       this.makeFileUnique(aLocalFile);
  211.  
  212.       if (aLocalFile.isExecutable() && !this.mLauncher.targetFile.isExecutable()) {
  213.         var f = aLocalFile.clone();
  214.         aLocalFile.leafName = aLocalFile.leafName + "." + this.mLauncher.MIMEInfo.primaryExtension; 
  215.  
  216.         f.remove(false);
  217.         this.makeFileUnique(aLocalFile);
  218.       }
  219.       return aLocalFile;
  220.     },
  221.  
  222.     makeFileUnique: function (aLocalFile)
  223.     {
  224.       try {
  225.         // Since we're automatically downloading, we don't get the file picker's 
  226.         // logic to check for existing files, so we need to do that here.
  227.         //
  228.         // Note - this code is identical to that in 
  229.         //   toolkit/content/contentAreaUtils.js.
  230.         // If you are updating this code, update that code too! We can't share code
  231.         // here since this is called in a js component. 
  232.         var collisionCount = 0;
  233.         while (aLocalFile.exists()) {
  234.           collisionCount++;
  235.           if (collisionCount == 1) {
  236.             // Append "(2)" before the last dot in (or at the end of) the filename
  237.             // special case .ext.gz etc files so we don't wind up with .tar(2).gz
  238.             if (aLocalFile.leafName.match(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i)) {
  239.               aLocalFile.leafName = aLocalFile.leafName.replace(/\.[^\.]{1,3}\.(gz|bz2|Z)$/i, "(2)$&");
  240.             }
  241.             else {
  242.               aLocalFile.leafName = aLocalFile.leafName.replace(/(\.[^\.]*)?$/, "(2)$&");
  243.             }
  244.           }
  245.           else {
  246.             // replace the last (n) in the filename with (n+1)
  247.             aLocalFile.leafName = aLocalFile.leafName.replace(/^(.*\()\d+\)/, "$1" + (collisionCount+1) + ")");
  248.           }
  249.         }
  250.         aLocalFile.create(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  251.       }
  252.       catch (e) {
  253.         dump("*** exception in validateLeafName: " + e + "\n");
  254.         if (aLocalFile.leafName == "" || aLocalFile.isDirectory()) {
  255.           aLocalFile.append("unnamed");
  256.           if (aLocalFile.exists())
  257.             aLocalFile.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0600);
  258.         }
  259.       }
  260.     },
  261.     
  262.     // ---------- implementation methods ----------
  263.  
  264.     // Web progress listener so we can detect errors while mLauncher is
  265.     // streaming the data to a temporary file.
  266.     progressListener: {
  267.         // Implementation properties.
  268.         helperAppDlg: null,
  269.  
  270.         // nsIWebProgressListener methods.
  271.         // Look for error notifications and display alert to user.
  272.         onStatusChange: function( aWebProgress, aRequest, aStatus, aMessage ) {
  273.             if ( aStatus != Components.results.NS_OK ) {
  274.                 // Get prompt service.
  275.                 var prompter = Components.classes[ "@mozilla.org/embedcomp/prompt-service;1" ]
  276.                                    .getService( Components.interfaces.nsIPromptService );
  277.                 // Display error alert (using text supplied by back-end).
  278.                 prompter.alert( this.dialog, this.helperAppDlg.mTitle, aMessage );
  279.  
  280.                 // Close the dialog.
  281.                 this.helperAppDlg.onCancel();
  282.                 if ( this.helperAppDlg.mDialog ) {
  283.                     this.helperAppDlg.mDialog.close();
  284.                 }
  285.             }
  286.         },
  287.  
  288.         // Ignore onProgressChange, onStateChange, onLocationChange, and onSecurityChange notifications.
  289.         onProgressChange: function( aWebProgress,
  290.                                     aRequest,
  291.                                     aCurSelfProgress,
  292.                                     aMaxSelfProgress,
  293.                                     aCurTotalProgress,
  294.                                     aMaxTotalProgress ) {
  295.         },
  296.  
  297.         onProgressChange64: function( aWebProgress,
  298.                                       aRequest,
  299.                                       aCurSelfProgress,
  300.                                       aMaxSelfProgress,
  301.                                       aCurTotalProgress,
  302.                                       aMaxTotalProgress ) {
  303.         },
  304.  
  305.  
  306.  
  307.         onStateChange: function( aWebProgress, aRequest, aStateFlags, aStatus ) {
  308.         },
  309.  
  310.         onLocationChange: function( aWebProgress, aRequest, aLocation ) {
  311.         },
  312.  
  313.         onSecurityChange: function( aWebProgress, aRequest, state ) {
  314.         }
  315.     },
  316.  
  317.     // initDialog:  Fill various dialog fields with initial content.
  318.     initDialog : function() {
  319.       // Put file name in window title.
  320.       var suggestedFileName = this.mLauncher.suggestedFileName;
  321.  
  322.       // Some URIs do not implement nsIURL, so we can't just QI.
  323.       var url   = this.mLauncher.source;
  324.       var fname = "";
  325.       this.mSourcePath = url.prePath;
  326.       try {
  327.           url = url.QueryInterface( Components.interfaces.nsIURL );
  328.           // A url, use file name from it.
  329.           fname = url.fileName;
  330.           this.mSourcePath += url.directory;
  331.       } catch (ex) {
  332.           // A generic uri, use path.
  333.           fname = url.path;
  334.           this.mSourcePath += url.path;
  335.       }
  336.  
  337.       if (suggestedFileName)
  338.         fname = suggestedFileName;
  339.       
  340.       var displayName = fname.replace(/ +/g, " ");
  341.  
  342.       this.mTitle = this.dialogElement("strings").getFormattedString("title", [displayName]);
  343.       this.mDialog.document.title = this.mTitle;
  344.  
  345.       // Put content type, filename and location into intro.
  346.       this.initIntro(url, fname, displayName);
  347.  
  348.       var iconString = "moz-icon://" + fname + "?size=16&contentType=" + this.mLauncher.MIMEInfo.MIMEType;
  349.       this.dialogElement("contentTypeImage").setAttribute("src", iconString);
  350.  
  351.       this.initAppAndSaveToDiskValues();
  352.  
  353.       // Initialize "always ask me" box. This should always be disabled
  354.       // and set to true for the ambiguous type application/octet-stream.
  355.       // We don't also check for application/x-msdownload here since we
  356.       // want users to be able to autodownload .exe files. 
  357.       var rememberChoice = this.dialogElement("rememberChoice");
  358.  
  359. //@line 424 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  360.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  361.       if (mimeType == "application/octet-stream" || 
  362.           mimeType == "application/x-msdownload" ||
  363.           this.mLauncher.targetFile.isExecutable()) {
  364.         rememberChoice.checked = false;
  365.         rememberChoice.disabled = true;
  366.       }
  367.       else {
  368.         rememberChoice.checked = !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  369.       }
  370.       this.toggleRememberChoice(rememberChoice);
  371.  
  372.       // XXXben - menulist won't init properly, hack. 
  373.       var openHandler = this.dialogElement("openHandler");
  374.       openHandler.parentNode.removeChild(openHandler);
  375.       var openHandlerBox = this.dialogElement("openHandlerBox");
  376.       openHandlerBox.appendChild(openHandler);
  377.  
  378.       this.mDialog.setTimeout("dialog.postShowCallback()", 0);
  379.       
  380.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  381.       const nsITimer = Components.interfaces.nsITimer;
  382.       this._timer = Components.classes["@mozilla.org/timer;1"]
  383.                               .createInstance(nsITimer);
  384.       this._timer.initWithCallback(this, 250, nsITimer.TYPE_ONE_SHOT);
  385.     },
  386.     
  387.     _timer: null,
  388.     notify: function (aTimer) {
  389.       try { // The user may have already canceled the dialog.
  390.         if (!this._blurred)
  391.           this.mDialog.document.documentElement.getButton('accept').disabled = false;
  392.       } catch (ex) {}
  393.       this._delayExpired = true;
  394.       this._timer = null; // the timer won't release us, so we have to release it
  395.     },
  396.     
  397.     postShowCallback: function () {
  398.       this.mDialog.sizeToContent();
  399.  
  400.       // Set initial focus
  401.       this.dialogElement("mode").focus();
  402.     },
  403.  
  404.     // initIntro:
  405.     initIntro: function(url, filename, displayname) {
  406.         this.dialogElement( "location" ).value = displayname;
  407.         this.dialogElement( "location" ).setAttribute("realname", filename);
  408.         this.dialogElement( "location" ).setAttribute("tooltiptext", displayname);
  409.  
  410.         // if mSourcePath is a local file, then let's use the pretty path name instead of an ugly
  411.         // url...
  412.         var pathString = this.mSourcePath;
  413.         try 
  414.         {
  415.           var fileURL = url.QueryInterface(Components.interfaces.nsIFileURL);
  416.           if (fileURL)
  417.           {
  418.             var fileObject = fileURL.file;
  419.             if (fileObject)
  420.             {
  421.               var parentObject = fileObject.parent;
  422.               if (parentObject)
  423.               {
  424.                 pathString = parentObject.path;
  425.               }
  426.             }
  427.           }
  428.         } catch(ex) {}
  429.  
  430.         if (pathString == this.mSourcePath)
  431.         {
  432.           // wasn't a fileURL
  433.           var tmpurl = url.clone(); // don't want to change the real url
  434.           try {
  435.             tmpurl.userPass = "";
  436.           } catch (ex) {}
  437.           pathString = tmpurl.prePath;
  438.         }
  439.  
  440.         // Set the location text, which is separate from the intro text so it can be cropped
  441.         var location = this.dialogElement( "source" );
  442.         location.value = pathString;
  443.         location.setAttribute("tooltiptext", this.mSourcePath);
  444.         
  445.         // Show the type of file. 
  446.         var type = this.dialogElement("type");
  447.         var mimeInfo = this.mLauncher.MIMEInfo;
  448.         
  449.         // 1. Try to use the pretty description of the type, if one is available.
  450.         var typeString = mimeInfo.description;
  451.         
  452.         if (typeString == "") {
  453.           // 2. If there is none, use the extension to identify the file, e.g. "ZIP file"
  454.           var primaryExtension = "";
  455.           try {
  456.             primaryExtension = mimeInfo.primaryExtension;
  457.           }
  458.           catch (ex) {
  459.           }
  460.           if (primaryExtension != "")
  461.             typeString = primaryExtension.toUpperCase() + " file";
  462.           // 3. If we can't even do that, just give up and show the MIME type. 
  463.           else
  464.             typeString = mimeInfo.MIMEType;
  465.         }
  466.         
  467.         type.value = typeString;
  468.     },
  469.     
  470.     _blurred: false,
  471.     _delayExpired: false, 
  472.     onBlur: function(aEvent) {
  473.       if (aEvent.target != this.mDialog.document)
  474.         return;
  475.       this._blurred = true;
  476.       this.mDialog.document.documentElement.getButton("accept").disabled = true;
  477.     },
  478.     
  479.     onFocus: function(aEvent) {
  480.       if (aEvent.target != this.mDialog.document)
  481.         return;
  482.       this._blurred = false;
  483.       if (this._delayExpired) {
  484.         var script = "document.documentElement.getButton('accept').disabled = false";
  485.         this.mDialog.setTimeout(script, 250);
  486.       }
  487.     },
  488.  
  489.     // Returns true if opening the default application makes sense.
  490.     openWithDefaultOK: function() {
  491.         var result;
  492.  
  493.         // The checking is different on Windows...
  494. //@line 559 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  495.         // Windows presents some special cases.
  496.         // We need to prevent use of "system default" when the file is
  497.         // executable (so the user doesn't launch nasty programs downloaded
  498.         // from the web), and, enable use of "system default" if it isn't
  499.         // executable (because we will prompt the user for the default app
  500.         // in that case).
  501.         
  502.         // Need to get temporary file and check for executable-ness.
  503.         var tmpFile = this.mLauncher.targetFile;
  504.         
  505.         //  Default is Ok if the file isn't executable (and vice-versa).
  506.         return !tmpFile.isExecutable();
  507. //@line 577 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  508.     },
  509.     
  510.     // Set "default" application description field.
  511.     initDefaultApp: function() {
  512.       // Use description, if we can get one.
  513.       var desc = this.mLauncher.MIMEInfo.defaultDescription;
  514.       if (desc) {
  515.         var defaultApp = this.dialogElement("strings").getFormattedString("defaultApp", [desc]);
  516.         this.dialogElement("defaultHandler").label = defaultApp;
  517.       }
  518.       else {
  519.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "1");
  520.         // Hide the default handler item too, in case the user picks a 
  521.         // custom handler at a later date which triggers the menulist to show.
  522.         this.dialogElement("defaultHandler").hidden = true;
  523.       }
  524.     },
  525.  
  526.     // getPath:
  527.     getPath: function (aFile) {
  528. //@line 600 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  529.       return aFile.path;
  530. //@line 602 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  531.     },
  532.  
  533.     // initAppAndSaveToDiskValues:
  534.     initAppAndSaveToDiskValues: function() {
  535.       var modeGroup = this.dialogElement("mode");
  536.  
  537.       // We don't let users open .exe files or random binary data directly 
  538.       // from the browser at the moment because of security concerns. 
  539.       var openWithDefaultOK = this.openWithDefaultOK();
  540.       var mimeType = this.mLauncher.MIMEInfo.MIMEType;
  541.       if (this.mLauncher.targetFile.isExecutable() || (
  542.           (mimeType == "application/octet-stream" ||
  543.            mimeType == "application/x-msdownload") && 
  544.            !openWithDefaultOK)) {
  545.         this.dialogElement("open").disabled = true;
  546.         var openHandler = this.dialogElement("openHandler");
  547.         openHandler.disabled = true;
  548.         openHandler.selectedItem = null;
  549.         modeGroup.selectedItem = this.dialogElement("save");
  550.         return;
  551.       }
  552.     
  553.       // Fill in helper app info, if there is any.
  554.       this.chosenApp = this.mLauncher.MIMEInfo.preferredApplicationHandler;
  555.       // Initialize "default application" field.
  556.       this.initDefaultApp();
  557.  
  558.       var otherHandler = this.dialogElement("otherHandler");
  559.               
  560.       // Fill application name textbox.
  561.       if (this.chosenApp && this.chosenApp.path) {
  562.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  563.         otherHandler.label = this.chosenApp.leafName;
  564.         otherHandler.hidden = false;
  565.       }
  566.  
  567.       var useDefault = this.dialogElement("useSystemDefault");
  568.       var openHandler = this.dialogElement("openHandler");
  569.       openHandler.selectedIndex = 0;
  570.  
  571.       if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useSystemDefault) {
  572.         // Open (using system default).
  573.         modeGroup.selectedItem = this.dialogElement("open");
  574.       } else if (this.mLauncher.MIMEInfo.preferredAction == this.nsIMIMEInfo.useHelperApp) {
  575.         // Open with given helper app.
  576.         modeGroup.selectedItem = this.dialogElement("open");
  577.         openHandler.selectedIndex = 1;
  578.       } else {
  579.         // Save to disk.
  580.         modeGroup.selectedItem = this.dialogElement("save");
  581.       }
  582.       
  583.       // If we don't have a "default app" then disable that choice.
  584.       if (!openWithDefaultOK) {
  585.         var useDefault = this.dialogElement("defaultHandler");
  586.         var isSelected = useDefault.selected;
  587.         
  588.         // Disable that choice.
  589.         useDefault.hidden = true;
  590.         // If that's the default, then switch to "save to disk."
  591.         if (isSelected) {
  592.           openHandler.selectedIndex = 1;
  593.           modeGroup.selectedItem = this.dialogElement("save");
  594.         }
  595.       }
  596.       
  597.       // otherHandler is always disabled on Mac
  598. //@line 673 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  599.       otherHandler.nextSibling.hidden = otherHandler.nextSibling.nextSibling.hidden = false;
  600. //@line 675 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  601.       this.updateOKButton();
  602.     },
  603.  
  604.     // Returns the user-selected application
  605.     helperAppChoice: function() {
  606.       return this.chosenApp;
  607.     },
  608.     
  609.     get saveToDisk() {
  610.       return this.dialogElement("save").selected;
  611.     },
  612.     
  613.     get useOtherHandler() {
  614.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 1;
  615.     },
  616.     
  617.     get useSystemDefault() {
  618.       return this.dialogElement("open").selected && this.dialogElement("openHandler").selectedIndex == 0;
  619.     },
  620.     
  621.     toggleRememberChoice: function (aCheckbox) {
  622.         this.dialogElement("settingsChange").hidden = !aCheckbox.checked;
  623.         this.mDialog.sizeToContent();
  624.     },
  625.     
  626.     openHandlerCommand: function () {
  627.       var openHandler = this.dialogElement("openHandler");
  628.       if (openHandler.selectedItem.id == "choose")
  629.         this.chooseApp();
  630.       else
  631.         openHandler.setAttribute("lastSelectedItemID", openHandler.selectedItem.id);
  632.     },
  633.  
  634.     updateOKButton: function() {
  635.       var ok = false;
  636.       if (this.dialogElement("save").selected) {
  637.         // This is always OK.
  638.         ok = true;
  639.       } 
  640.       else if (this.dialogElement("open").selected) {
  641.         switch (this.dialogElement("openHandler").selectedIndex) {
  642.         case 0:
  643.           // No app need be specified in this case.
  644.           ok = true;
  645.           break;
  646.         case 1:
  647.           // only enable the OK button if we have a default app to use or if 
  648.           // the user chose an app....
  649.           ok = this.chosenApp || /\S/.test(this.dialogElement("otherHandler").getAttribute("path")); 
  650.         break;
  651.         }
  652.       }
  653.  
  654.       // Enable Ok button if ok to press.
  655.       this.mDialog.document.documentElement.getButton("accept").disabled = !ok;
  656.     },
  657.     
  658.     // Returns true iff the user-specified helper app has been modified.
  659.     appChanged: function() {
  660.       return this.helperAppChoice() != this.mLauncher.MIMEInfo.preferredApplicationHandler;
  661.     },
  662.  
  663.     updateMIMEInfo: function() {
  664.       var needUpdate = false;
  665.       // If current selection differs from what's in the mime info object,
  666.       // then we need to update.
  667.       if (this.saveToDisk) {
  668.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.saveToDisk;
  669.         if (needUpdate)
  670.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.saveToDisk;
  671.       } 
  672.       else if (this.useSystemDefault) {
  673.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useSystemDefault;
  674.         if (needUpdate)
  675.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useSystemDefault;
  676.       } 
  677.       else {
  678.         // For "open with", we need to check both preferred action and whether the user chose
  679.         // a new app.
  680.         needUpdate = this.mLauncher.MIMEInfo.preferredAction != this.nsIMIMEInfo.useHelperApp || this.appChanged();
  681.         if (needUpdate) {
  682.           this.mLauncher.MIMEInfo.preferredAction = this.nsIMIMEInfo.useHelperApp;
  683.           // App may have changed - Update application and description
  684.           var app = this.helperAppChoice();
  685.           this.mLauncher.MIMEInfo.preferredApplicationHandler = app;
  686.           this.mLauncher.MIMEInfo.applicationDescription = "";
  687.         }
  688.       }
  689.       // We will also need to update if the "always ask" flag has changed.
  690.       needUpdate = needUpdate || this.mLauncher.MIMEInfo.alwaysAskBeforeHandling != (!this.dialogElement("rememberChoice").checked);
  691.  
  692.       // One last special case: If the input "always ask" flag was false, then we always
  693.       // update.  In that case we are displaying the helper app dialog for the first
  694.       // time for this mime type and we need to store the user's action in the mimeTypes.rdf
  695.       // data source (whether that action has changed or not; if it didn't change, then we need
  696.       // to store the "always ask" flag so the helper app dialog will or won't display
  697.       // next time, per the user's selection).
  698.       needUpdate = needUpdate || !this.mLauncher.MIMEInfo.alwaysAskBeforeHandling;
  699.  
  700.       // Make sure mime info has updated setting for the "always ask" flag.
  701.       this.mLauncher.MIMEInfo.alwaysAskBeforeHandling = !this.dialogElement("rememberChoice").checked;
  702.  
  703.       return needUpdate;        
  704.     },
  705.     
  706.     // See if the user changed things, and if so, update the
  707.     // mimeTypes.rdf entry for this mime type.
  708.     updateHelperAppPref: function() {
  709.       var ha = new this.mDialog.HelperApps();
  710.       ha.updateTypeInfo(this.mLauncher.MIMEInfo);
  711.     },
  712.     
  713.     // onOK:
  714.     onOK: function() {
  715.       // Verify typed app path, if necessary.
  716.       if (this.useOtherHandler) {
  717.         var helperApp = this.helperAppChoice();
  718.         if (!helperApp || !helperApp.exists()) {
  719.           // Show alert and try again.        
  720.           var bundle = this.dialogElement("strings");                    
  721.           var msg = bundle.getFormattedString("badApp", [this.dialogElement("otherHandler").path]);
  722.           var svc = Components.classes["@mozilla.org/embedcomp/prompt-service;1"].getService(Components.interfaces.nsIPromptService);
  723.           svc.alert(this.mDialog, bundle.getString("badApp.title"), msg);
  724.  
  725.           // Disable the OK button.
  726.           this.mDialog.document.documentElement.getButton("accept").disabled = true;
  727.           this.dialogElement("mode").focus();          
  728.  
  729.           // Clear chosen application.
  730.           this.chosenApp = null;
  731.  
  732.           // Leave dialog up.
  733.           return false;
  734.         }
  735.       }
  736.         
  737.       // Remove our web progress listener (a progress dialog will be
  738.       // taking over).
  739.       this.mLauncher.setWebProgressListener(null);
  740.       
  741.       // saveToDisk and launchWithApplication can return errors in 
  742.       // certain circumstances (e.g. The user clicks cancel in the
  743.       // "Save to Disk" dialog. In those cases, we don't want to
  744.       // update the helper application preferences in the RDF file.
  745.       try {
  746.         var needUpdate = this.updateMIMEInfo();
  747.         
  748.         if (this.dialogElement("save").selected) {
  749.           // If we're using a default download location, create a path
  750.           // for the file to be saved to to pass to |saveToDisk| - otherwise
  751.           // we must ask the user to pick a save name.
  752.  
  753. //@line 841 "/c/mozilla/toolkit/mozapps/downloads/src/nsHelperAppDlg.js.in"
  754.           this.mLauncher.saveToDisk(null, false);
  755.         }
  756.         else
  757.           this.mLauncher.launchWithApplication(null, false);
  758.  
  759.         // Update user pref for this mime type (if necessary). We do not
  760.         // store anything in the mime type preferences for the ambiguous
  761.         // type application/octet-stream. We do NOT do this for 
  762.         // application/x-msdownload since we want users to be able to 
  763.         // autodownload these to disk. 
  764.         if (needUpdate && this.mLauncher.MIMEInfo.MIMEType != "application/octet-stream")
  765.           this.updateHelperAppPref();
  766.       } catch(e) { }
  767.  
  768.       // Unhook dialog from this object.
  769.       this.mDialog.dialog = null;
  770.  
  771.       // Close up dialog by returning true.
  772.       return true;
  773.     },
  774.  
  775.     // onCancel:
  776.     onCancel: function() {
  777.       // Remove our web progress listener.
  778.       this.mLauncher.setWebProgressListener(null);
  779.  
  780.       // Cancel app launcher.
  781.       try {
  782.         const NS_BINDING_ABORTED = 0x804b0002;
  783.         this.mLauncher.cancel(NS_BINDING_ABORTED);
  784.       } catch(exception) {
  785.       }
  786.  
  787.       // Unhook dialog from this object.
  788.       this.mDialog.dialog = null;
  789.  
  790.       // Close up dialog by returning true.
  791.       return true;
  792.     },
  793.  
  794.     // dialogElement:  Convenience. 
  795.     dialogElement: function(id) {
  796.       return this.mDialog.document.getElementById(id);
  797.     },
  798.  
  799.     // chooseApp:  Open file picker and prompt user for application.
  800.     chooseApp: function() {
  801.       var nsIFilePicker = Components.interfaces.nsIFilePicker;
  802.       var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(nsIFilePicker);
  803.       fp.init(this.mDialog,
  804.               this.dialogElement("strings").getString("chooseAppFilePickerTitle"),
  805.               nsIFilePicker.modeOpen);
  806.  
  807.       fp.appendFilters(nsIFilePicker.filterApps);
  808.  
  809.       if (fp.show() == nsIFilePicker.returnOK && fp.file) {
  810.         // Show the "handler" menulist since we have a (user-specified) 
  811.         // application now.
  812.         this.dialogElement("modeDeck").setAttribute("selectedIndex", "0");
  813.         
  814.         // Remember the file they chose to run.
  815.         this.chosenApp = fp.file;
  816.         // Update dialog.
  817.         var otherHandler = this.dialogElement("otherHandler");
  818.         otherHandler.removeAttribute("hidden");
  819.         otherHandler.setAttribute("path", this.getPath(this.chosenApp));
  820.         otherHandler.label = this.chosenApp.leafName;
  821.         this.dialogElement("openHandler").selectedIndex = 1;
  822.         this.dialogElement("openHandler").setAttribute("lastSelectedItemID", "otherHandler");
  823.         
  824.         this.dialogElement("mode").selectedItem = this.dialogElement("open");
  825.       }
  826.       else {
  827.         var openHandler = this.dialogElement("openHandler");
  828.         var lastSelectedID = openHandler.getAttribute("lastSelectedItemID");
  829.         if (!lastSelectedID)
  830.           lastSelectedID = "defaultHandler";
  831.         openHandler.selectedItem = this.dialogElement(lastSelectedID);
  832.       }
  833.     },
  834.  
  835.     // Turn this on to get debugging messages.
  836.     debug: false,
  837.  
  838.     // Dump text (if debug is on).
  839.     dump: function( text ) {
  840.         if ( this.debug ) {
  841.             dump( text ); 
  842.         }
  843.     },
  844.  
  845.     // dumpInfo:
  846.     doDebug: function() {
  847.         const nsIProgressDialog = Components.interfaces.nsIProgressDialog;
  848.         // Open new progress dialog.
  849.         var progress = Components.classes[ "@mozilla.org/progressdialog;1" ]
  850.                          .createInstance( nsIProgressDialog );
  851.         // Show it.
  852.         progress.open( this.mDialog );
  853.     },
  854.  
  855.     // dumpObj:
  856.     dumpObj: function( spec ) {
  857.          var val = "<undefined>";
  858.          try {
  859.              val = eval( "this."+spec ).toString();
  860.          } catch( exception ) {
  861.          }
  862.          this.dump( spec + "=" + val + "\n" );
  863.     },
  864.  
  865.     // dumpObjectProperties
  866.     dumpObjectProperties: function( desc, obj ) {
  867.          for( prop in obj ) {
  868.              this.dump( desc + "." + prop + "=" );
  869.              var val = "<undefined>";
  870.              try {
  871.                  val = obj[ prop ];
  872.              } catch ( exception ) {
  873.              }
  874.              this.dump( val + "\n" );
  875.          }
  876.     }
  877. }
  878.  
  879. // This Component's module implementation.  All the code below is used to get this
  880. // component registered and accessible via XPCOM.
  881. var module = {
  882.     firstTime: true,
  883.  
  884.     // registerSelf: Register this component.
  885.     registerSelf: function (compMgr, fileSpec, location, type) {
  886.         if (this.firstTime) {
  887.             this.firstTime = false;
  888.             throw Components.results.NS_ERROR_FACTORY_REGISTER_AGAIN;
  889.         }
  890.         compMgr = compMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
  891.  
  892.         compMgr.registerFactoryLocation( this.cid,
  893.                                          "Unknown Content Type Dialog",
  894.                                          this.contractId,
  895.                                          fileSpec,
  896.                                          location,
  897.                                          type );
  898.     },
  899.  
  900.     // getClassObject: Return this component's factory object.
  901.     getClassObject: function (compMgr, cid, iid) {
  902.         if (!cid.equals(this.cid)) {
  903.             throw Components.results.NS_ERROR_NO_INTERFACE;
  904.         }
  905.  
  906.         if (!iid.equals(Components.interfaces.nsIFactory)) {
  907.             throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
  908.         }
  909.  
  910.         return this.factory;
  911.     },
  912.  
  913.     /* CID for this class */
  914.     cid: Components.ID("{F68578EB-6EC2-4169-AE19-8C6243F0ABE1}"),
  915.  
  916.     /* Contract ID for this class */
  917.     contractId: "@mozilla.org/helperapplauncherdialog;1",
  918.  
  919.     /* factory object */
  920.     factory: {
  921.         // createInstance: Return a new nsProgressDialog object.
  922.         createInstance: function (outer, iid) {
  923.             if (outer != null)
  924.                 throw Components.results.NS_ERROR_NO_AGGREGATION;
  925.  
  926.             return (new nsUnknownContentTypeDialog()).QueryInterface(iid);
  927.         }
  928.     },
  929.  
  930.     // canUnload: n/a (returns true)
  931.     canUnload: function(compMgr) {
  932.         return true;
  933.     }
  934. };
  935.  
  936. // NSGetModule: Return the nsIModule object.
  937. function NSGetModule(compMgr, fileSpec) {
  938.     return module;
  939. }
  940.